import { Button, Form, Input, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import React from "react";
import { Link, useNavigate } from "react-router-dom";
import "./Login.less";
import { LoginApi } from "request/api";
const loginPic = require("./assets/logo.png");

export default function Login() {
  const navigate = useNavigate();
  const onFinish = (values: any) => {
    console.log("Success:", values);
    const res = {
      data: {
        avatar: "avatar.jpg",
        "cms-token": "eyJhbGcioiJIUzIINiIsInRS",
        username: "关羽",
      },
      errCode: 0,
      message: "登录成功",
    };
    //获取用户名和密码
    let { username, password } = values;
    LoginApi({ username, password }).then((res: any) => {
      console.log(res);
      if (res.errCode === 0) {
        message.success(res.message);

        // 保存用户信息和token
        // localStorage || react-redux
        localStorage.setItem("cms-username", res.data.username);
        localStorage.setItem("cms-token", res.data["cms-token"]);
        localStorage.setItem("cms-avatar", res.data.avatar); //环境变量
        localStorage.setItem("cms-player", res.data.player);
        localStorage.setItem("cms-editable", res.data.editable);

        //跳转登录页
        setTimeout(() => {
          navigate("/");
        }, 1500);
      } else {
        message.error(res.message);
      }
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className='login_box'>
      <img src={loginPic} className='logo' alt='' />
      <Form
        name='basic'
        wrapperCol={{ span: 24 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
      >
        <Form.Item
          name='username'
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input
            prefix={<UserOutlined className='site-form-item-icon' />}
            placeholder='请输入用户名'
          />
        </Form.Item>

        <Form.Item
          name='password'
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password
            prefix={<LockOutlined className='site-form-item-icon' />}
            placeholder='请输入密码'
          />
        </Form.Item>

        <Form.Item>
          <Link to='/register'>还没账号？立即注册</Link>
        </Form.Item>

        <Form.Item>
          <Button type='primary' block size='large' htmlType='submit'>
            登 录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
